import {Button, Form, Row, Col, Input, message, Space} from 'antd'
import React, {useState, useEffect} from 'react'
import {connect, history} from 'umi'
import type {ColumnsType} from 'antd/es/table'
import {
	PlusOutlined,
	ArrowUpOutlined,
	ArrowDownOutlined,
	DeleteOutlined,
} from '@ant-design/icons'
import moment from 'moment'
import styles from './index.less'
import CustomTable from '@/components/Table'
import Modal from '@/components/Modal'
import {
	amcparkingstorageInfo,
	editAmcparkingstorage,
	getImportStorageData,
	getSupplierBaseExcelList,
} from '@/service/storage/parkingLot'
import {modalApi} from '@/utils/modalReq'
import {downloadDocumentUrl} from '@/service/common/download'
import BatchUpload from '@/components/BatchUpload'
import OperationRecord from '@/components/OperationRecord'

type DataType = {
	id?: string
	parkId?: string
	storageCode: string
	storageStatus?: number
	createStoreTime?: string
	createPerson?: string
}

const edit = (props: any) => {
	const {query} = props.location
	const [form] = Form.useForm()
	const [form2] = Form.useForm()
	const [type, setType] = useState<string>()
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [deleteModalOpen, setDeleteModalOpen] = useState(false)
	const [dataSource, setDataSource] = useState<DataType[]>([])
	const [datas, setDatas] = useState<DataType[]>([])
	const [selectId, setSelectId] = useState('')
	const [total, setTotal] = useState(0)
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [isUploadModalOpen, setIsUploadModalOpen] = useState(false)
	console.log(dataSource, 'dataSource----')
	// 根据路由判断当前页面状态
	useEffect(() => {
		const hrefs = window.location.href
		if (hrefs.includes('view')) {
			setType('view')
		} else {
			setType('edit')
		}
	}, [])

	const getData = () => {
		amcparkingstorageInfo(query?.id).then((res: any) => {
			if (res?.data) {
				const newData = res.data?.map(
					(item: {
						createPerson: any
						storageStatus: number
						storageCode: string
						createUser: string
						createStoreTime: string
						carNo: string
					}) => ({
						parkId: query.id,
						storageCode: item.storageCode,
						storageStatus: item.storageStatus,
						createStoreTime: item.createStoreTime,
						createPerson: item?.createPerson,
						carNo: item?.carNo,
					}),
				)
				setDataSource(newData)
				setTotal(newData.length)
			}
		})
	}
	useEffect(() => {
		if (query?.id) {
			form.setFieldsValue({warehouseName: query?.name})
			getData()
		}
	}, [query])
	useEffect(() => {
		const num = (params.current - 1) * params.size
		const data = dataSource.slice(num, params.current * params.size)
		if (data?.length === 0 && params.current !== 1) {
			setParams({
				current: params.current - 1,
				size: params.size,
			})
		}
		setDatas(data)
	}, [params, dataSource])
	useEffect(() => {
		setTotal(dataSource.length)
	}, [dataSource])

	const onSave = async () => {
		setIsModalOpen(true)
	}
	const onSubmit = () => {
		const newDataSource = dataSource?.map((item) => {
			const newData: any = {...item}
			delete newData.carNo
			return newData
		})
		editAmcparkingstorage({parkId: query.id, storageList: newDataSource})
			.then((res: any) => {
				if (res.success) {
					message.success(res.msg)
					history.goBack()
				}
			})
			.catch((err: any) => {
				message.error(err)
			})
	}

	const columns: ColumnsType<DataType> = [
		{
			title: '库位代码',
			dataIndex: 'storageCode',
		},
		{
			title: '状态',
			dataIndex: 'storageStatus',
			render: (text) => <>{text === 1 ? '空置' : '已占用'}</>,
		},
		{
			title: '车牌号',
			dataIndex: 'carNo',
			width: 120,
		},
		{
			title: '创建时间',
			dataIndex: 'createStoreTime',
		},
		{
			title: '操作员',
			dataIndex: 'createPerson',
		},
	]
	const addData = async () => {
		const newData = [...dataSource]
		const value = await form2.validateFields()
		if (value?.socialCreditCode) {
			const data = newData.find(
				(item) => item?.storageCode === value?.socialCreditCode,
			)
			if (data) {
				message.warning('该库位代码已存在')
			} else {
				newData.unshift({
					parkId: query.id,
					storageCode: value.socialCreditCode,
					storageStatus: 1,
					createStoreTime: moment().format('YYYY-MM-DD HH:mm:ss'),
					createPerson: props?.user?.userName,
				})
				setDataSource(newData)
				form2.resetFields()
			}
		} else {
			message.warning('请输入库位代码')
		}
	}
	const deleteData = () => {
		const newData = dataSource.filter(
			(item) => !selectId.includes(item.storageCode),
		)
		setDataSource(newData)
		setDeleteModalOpen(false)
	}

	const errorColumns: ColumnsType<DataType> = [
		{
			title: '库位代码',
			dataIndex: 'storageCode',
			align: 'center',
			width: 120,
		},
		{
			title: '状态',
			dataIndex: 'storageStatusStr',
			align: 'center',
			width: 120,
		},
		{
			title: '失败原因',
			dataIndex: 'message',
			align: 'center',
			width: 200,
		},
	]

	return (
		<div className={styles.add}>
			<div className={styles.title}>基础信息</div>
			<Form
				form={form}
				name="basic"
				layout="horizontal"
				labelCol={{flex: '100px'}}
				labelAlign="right"
				labelWrap
				autoComplete="off"
				disabled={type === 'view'}>
				<Row gutter={12}>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="停车场"
							name="warehouseName"
							rules={[{required: true}]}>
							<Input placeholder="请输入" disabled />
						</Form.Item>
					</Col>
				</Row>
			</Form>
			<div className={styles.title}>库位明细</div>
			{type === 'edit' ? (
				<>
					<Form
						form={form2}
						name="detailed"
						layout="horizontal"
						labelCol={{flex: '100px'}}
						labelAlign="right"
						labelWrap
						autoComplete="off">
						<Row gutter={12}>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="库位代码"
									name="socialCreditCode">
									<Input placeholder="请输入" />
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Button
									icon={<PlusOutlined />}
									type="primary"
									ghost
									size="small"
									style={{margin: '3px 0 0 12px'}}
									onClick={addData}>
									新增
								</Button>
							</Col>
						</Row>
					</Form>
					<div className={styles.btnlist}>
						<Space size={12}>
							<Button
								icon={<DeleteOutlined />}
								className={styles.delete}
								ghost
								size="small"
								onClick={() => {
									if (selectId?.length) {
										setDeleteModalOpen(true)
									} else {
										message.warning('请先选择要删除的库位')
									}
								}}>
								删除
							</Button>
							<Button
								icon={<ArrowUpOutlined />}
								className={styles.warning}
								ghost
								size="small"
								onClick={() => {
									setIsUploadModalOpen(true)
								}}>
								导入
							</Button>
						</Space>
					</div>
				</>
			) : (
				''
			)}
			{type === 'view' ? (
				<div className={styles.btnlist}>
					<Button
						icon={<ArrowDownOutlined />}
						className={styles.import}
						ghost
						size="small"
						onClick={() => {
							downloadDocumentUrl({
								resourceId: '139',
								queryDesc:
									'停车场-库位档案-编辑,resourceId:139',
								queryParam: {parkId: query?.id},
							})
						}}>
						导出
					</Button>
				</div>
			) : (
				''
			)}
			<CustomTable
				params={params}
				columns={columns}
				pagination
				total={total}
				kid="storageCode"
				callback={(pagination: any) => {
					setParams(pagination)
				}}
				getCheckboxProps={{
					getCheckboxProps: (record: any) => ({
						disabled:
							type === 'edit' ? record.storageStatus === 2 : true,
					}),
				}}
				loading={false}
				dataSource={datas}
				showRowSelection
				selectCallback={(keys: any) => {
					setSelectId(() => keys?.join(','))
				}}
			/>
			{type === 'view' ? (
				<>
					<div className={styles.title}>操作记录</div>
					<OperationRecord businessId={query?.id} businessType={39} />
				</>
			) : (
				''
			)}
			<div className={styles.wrap}>
				{type === 'view' ? (
					<Button
						onClick={() => {
							history.go(-1)
						}}>
						返回
					</Button>
				) : (
					<>
						<Button
							type="primary"
							htmlType="submit"
							onClick={() => {
								onSave()
							}}>
							保存
						</Button>
						<Button
							onClick={() => {
								history.go(-1)
							}}>
							取消
						</Button>
					</>
				)}
			</div>
			<Modal
				text="确定要保存吗？请仔细核对所填信息"
				onSubmit={onSubmit}
				isModalOpen={isModalOpen}
				setIsModalOpen={setIsModalOpen}
			/>
			<Modal
				text="确认要删除所选数据吗？"
				onSubmit={deleteData}
				isModalOpen={deleteModalOpen}
				setIsModalOpen={setDeleteModalOpen}
			/>
			<BatchUpload
				temporaryData
				isModalOpen={isUploadModalOpen}
				setIsModalOpen={setIsUploadModalOpen}
				importData={getImportStorageData}
				onTableList={getSupplierBaseExcelList}
				getListData={getData}
				parkId={query?.id}
				downloadUrl="storage/库位导入.xlsx"
				uploadFileUrl={`${modalApi.storage}/amcparkingstorage/checkStorageData`}
				columns={errorColumns}
				sourceId={32}
				templateType="库位导入模板"
			/>
		</div>
	)
}
export default connect(({user}: any) => ({user}))(edit)
